﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ThreadTest
{
    class Program
    {
        static void Main(string[] args)
        {
            //ThreadStart threadStart = () => { };
            //Thread thread = new Thread(threadStart) { IsBackground = false };
            ////int a = 2;
            //Action<int> action1 = (int a) => { Console.WriteLine(a); };
            //action1(10);



            //test("132", "444");
            //string[] array = { "111", "2222", "3333" };
            //test(array);
            //List<string> list = new List<string>();
            //list.Add("000");
            //list.Add("123");
            //test(list.ToArray());

            // 异步等待：不阻塞线程
            //Console.WriteLine("开始");
            //Task[] tasks = new Task[] { Task.Delay(1000), Task.Delay(2000) };
            ////Task.Delay(5000);

            //Task.WhenAll(tasks).ContinueWith((t) =>
            //{
            //    Console.WriteLine("ContinueWith");
            //});
            //Console.WriteLine("结束");
            //Console.WriteLine("所有任务完成！"); // 2 秒后执行
            //Console.ReadLine();

            /*
             * 限制用10个线程完成多个任务
             * **/
            List<int> list = new List<int>();
            for (int i = 0; i < 200; i++)
            {
                list.Add(i);
            }

            Action<int> action = i =>
            {
                Console.WriteLine($"第{i}个任务，子线程" + Thread.CurrentThread.ManagedThreadId.ToString("00"));
                Thread.Sleep(new Random(i).Next(1000, 3000));
            };

            List<Task> tasks = new List<Task>();
            foreach (var i in list)
            {
                int k = i;
                tasks.Add(Task.Run(() => action(k)));
                if (tasks.Count > 9)
                {
                    Task.WaitAny(tasks.ToArray());      // 到此会等待10个中的任意一个完成 再继续
                    tasks = tasks.Where(task => task.Status != TaskStatus.RanToCompletion).ToList();    // Linq
                    // 或者
                    //tasks.RemoveAll(task => task.IsCompleted);
                }
            }
            Task.WhenAll(tasks.ToArray());
            while (true) ;



            
        }

        static void test(params string[] str)
        {
            foreach(var s in str)
            {
                Console.WriteLine(s);
            }
        }
    }
}
